<?php

namespace app\api\model;

use think\Model;

class UserToken extends Model
{

    public static function queryTokenByTokenStr($token)
    {
        return self::where("token", $token)->find();
    }

    public static function queryTokenByUserId($userId)
    {
        return self::where("user_id", $userId)->find();
    }

    public static function removeToken($tokenId)
    {
        return self::where('token_id', $tokenId)->delete();
    }

    public static function createToken($user)
    {
        $isToken = self::queryTokenByUserId($user['user_id']);
        $token = md5($user['user_id'] . $user['salt'] . time());
        if($isToken){
            $updateData = ['token' => $token,'expired_time' => time() + 43200];
            $whereData = ['user_id' => $user['user_id']];
            self::where($whereData)->update($updateData);
        }else{
            $creatData = [
                'user_id' => $user['user_id'],
                'token' => $token,
                'expired_time' => time() + 43200
            ];
            self::create($creatData);
        }

        return $token;
    }

}